package xml;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import javax.xml.bind.SchemaOutputResolver;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamResult;
import java.io.IOException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import palette.*;
//import java.util.List;

public class XmlWriter {
	JAXBContext ctx;
	Marshaller xmlWriter;
	
	// specify where the generated XML schema will be created
    final File dir = new File("generated" + File.separator + "schema");
    // output file for xmlWriter to write to
    OutputStream os;
    
    public XmlWriter() {
		initialize();
	    try {
	    	// specify a name for the generated XML instance document
	    	//os = new FileOutputStream("shapes.xml");
	    }catch (Exception e) {
	    	System.out.println("File not found");
	    	e.printStackTrace();
	    }
    }
    
	private void initialize() {
		try {
			ctx = JAXBContext.newInstance(ShapeCollection.class);
			xmlWriter = ctx.createMarshaller();
			xmlWriter.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, new Boolean(true));
			// generate an XML schema from the annotated object model; create it
	        // in the dir specified earlier under the default name, schema1.xsd
	        ctx.generateSchema(new SchemaOutputResolver() {
	               @Override
	               public Result createOutput(String namespaceUri, String schemaName) throws IOException {
	                    return new StreamResult(new File(dir, schemaName));
	               }
	        });
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void write(String xmlFileName) {
		try {
			os = new FileOutputStream(xmlFileName);
			xmlWriter.marshal(new ShapeCollection(CanvasManager.getInst().getShapeList(), CanvasManager.getInst().getArrowList()), os);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
